<template>
    <div class="address-container">
        <h2>添加地址</h2>
        
        <div class="input-section">
            <el-input 
                v-model="formData.name" 
                placeholder="请输入地址名称"
                clearable
              
            />
        </div>

        <div class="qrcode-section" v-if="shouldShowQrCode">
         
        </div>

        <div class="action-section">
            <el-button 
                type="primary" 
                @click="handleSubmit"
                :disabled="isSubmitting"
            >
                {{ isSubmitting ? '提交中...' : '提交' }}
            </el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, watch } from 'vue'
// import VueQrcode from 'vue-qrcode'
import { base64ToFile } from '../../utils/base64ToFile'
import { addAddress } from '../../apis/address/address'
import { uploadFile } from '../../utils/upload'
import { ElMessage } from 'element-plus'
import { debounce } from '../../utils/debounceUtil'

// 表单数据
const formData = reactive({
    name: "",
    qrcode: ""
})

const qrcodeValue=ref('');

watch(() => formData.name,debounce((newValue:string)=>{
    console.log(newValue);
    qrcodeValue.value=newValue;
    
},500))

// 二维码生成的Base64数据
const qrCodeBase64 = ref('')

// 提交状态
const isSubmitting = ref(false)

// 是否显示二维码（有名称且长度合适时显示）
const shouldShowQrCode = computed(() => {
    return formData.name.trim().length > 2
})

// 处理二维码生成完成事件
const handleQrCodeGenerated = (base64: string) => {
    qrCodeBase64.value = base64
}

// 提交表单
const handleSubmit = async () => {
    if (!formData.name.trim()) {
        ElMessage.warning('请输入地址名称')
        return
    }
    
    if (!qrCodeBase64.value) {
        ElMessage.warning('二维码生成中，请稍候')
        return
    }

    try {
        isSubmitting.value = true
        
        // 1. 转换Base64为文件
        const qrCodeFile = base64ToFile(
            qrCodeBase64.value,
            "qrcode.png",
            "image/png"
        )
        
        // 2. 上传二维码文件
        const uploadRes = await uploadFile(qrCodeFile)
        if (!uploadRes) {
            throw new Error('二维码上传失败')
        }
        
        // 3. 更新表单数据
        formData.qrcode = uploadRes.data.url
        
        // 4. 提交地址数据
        const addRes = await addAddress(formData)
        if (addRes) {
            ElMessage.success('地址添加成功')
            // 重置表单
            formData.name = ""
            formData.qrcode = ""
        } else {
            throw new Error('地址添加失败')
        }
    } catch (error) {
        console.error("提交失败:", error)
        ElMessage.error('操作失败，请重试')
    } finally {
        isSubmitting.value = false
    }
}
</script>

<style scoped>
.address-container {
    max-width: 500px;
    margin: 0 auto;
    padding: 20px;
}

.input-section {
    margin-bottom: 20px;
}

.qrcode-section {
    margin: 25px 0;
    text-align: center;
}

.action-section {
    margin-top: 20px;
    text-align: center;
}
</style>